package com.example.gpstest.Utils;

import android.content.Context;
import android.content.pm.PackageManager;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by Bonnie_Yao on 2020/3/24
 * Description:
 */
public class SHA {
    private SHA() {
    }

    public static String encrypt1(String data) {
        return encrypt(data, "SHA-1");
    }

    public static String encrypt224(String data) {
        return encrypt(data, "SHA-224");
    }

    public static String encrypt256(String data) {
        return encrypt(data, "SHA-256");
    }

    public static String encrypt384(String data) {
        return encrypt(data, "SHA-384");
    }

    public static String encrypt512(String data) {
        return encrypt(data, "SHA-512");
    }

    /**
     * 通过SHA加密
     *
     * @param data      原始数据
     * @param algorithm 算法(SHA-1，SHA-224，SHA-256，SHA-384，和SHA-512)
     */
    private static String encrypt(String data, String algorithm) {
        String result = null;

        try {
            byte[] dataBytes = data.getBytes();
            MessageDigest md5 = MessageDigest.getInstance(algorithm);
            md5.update(dataBytes);
            byte[] bytes = md5.digest();

            StringBuilder sb = new StringBuilder();
            for (byte b : bytes) {
                if (Integer.toHexString(0xFF & b).length() == 1) {
                    sb.append("a").append(Integer.toHexString(0xFF & b));
                } else {
                    sb.append(Integer.toHexString(0xFF & b));
                }
            }

            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取当前apk的版本号
     *
     * @param mContext
     * @return
     */
    public static int getVersionCode(Context mContext) {
        int versionCode = 0;
        try {
            //获取软件版本号，对应AndroidManifest.xml下android:versionCode
            versionCode = mContext.getPackageManager().
                    getPackageInfo(mContext.getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    /**
     * 获取当前apk的版本名
     *
     * @param context 上下文
     * @return
     */
    public static String getVersionName(Context context) {
        String versionName = "";
        try {
            //获取软件版本号，对应AndroidManifest.xml下android:versionName
            versionName = context.getPackageManager().
                    getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionName;
    }

}
